<?php
/*
Contact to Console Server Database
by quyenlv
*/

/* Connect to database */
mysql_connect("localhost","root","123456") or die ("Cannot connect to the database");
mysql_select_db("dscs_db") or die ("Database is not exited");

function GetInfo($getPort) {
	/* Split to each line of statistics to a row of array */
	$info_row = explode("$$", $getPort);

	$telnet_info = explode(" ", $info_row[0]);
	$ip_info = explode(" ", $info_row[3]);
	$status_info = explode(" ", $info_row[7]);
	
	$ret[0] = $telnet_info[2];
	$ret[2] = $status_info[4];
	
	if ($status_info[4] == "waiting")
	{
		$addr = $ip_info[5];	
		$octet = explode(".", $addr);	
		$ret[1] = "$octet[0].$octet[1].$octet[2].x";
	}	
	else
		$ret[1] = "0";

	return $ret;
}

/* Read statistic file and delete all blank line */
$file = array_filter(array_map("trim", file("showport")), "strlen");

/* Delete the first row */
unset ($file[0]);

$rearrange = array_values($file);

//fclose($file);
$para = 13;

for ($i = 0, $pnum = count($rearrange)/$para-1; $i < $pnum; $i++) {
		$offset = $i*$para;
		$port_info[$i] = $rearrange[$offset].'$$'.$rearrange[$offset+1].'$$'.$rearrange[$offset+2].'$$'.$rearrange[$offset+3].'$$'.$rearrange[$offset+4].'$$'.$rearrange[$offset+5].'$$'.$rearrange[$offset+6].'$$'.$rearrange[$offset+7].'$$'.$rearrange[$offset+8].'$$'.$rearrange[$offset+9].'$$'.$rearrange[$offset+10].'$$'.$rearrange[$offset+11].'$$'.$rearrange[$offset+12];
}

/* Delete all before inserting to db */
mysql_query("delete from switch");

for($i = 0; $i < $pnum; $i++) {
	$r = GetInfo($port_info[$i]);
	mysql_query("insert into switch (port, ip, status) values ('".$r[0]."', '".$r[1]."', '".$r[2]."')");
}

function getSwitchStatus() {
	$res = mysql_query("select developer.name, switch.port, port2model.model, developer.skype from developer, switch, port2model where developer.ip = switch.ip and switch.port = port2model.port");
	$not_exist = mysql_query("select * from port2model where port in (select a.port from switch a natural left join developer b where b.ip is null)");			
	
	$i = 0;
	$result = array();
	
	while($row = mysql_fetch_assoc($res)) {
		$result[$i] = $row;	
			
		/* Get user's image from gravartar with the size is 62x62 px */
		$gravatarMd5 = md5($row['name'].'@dasannetworks.com');
		$result[$i]['avatarUrl'] = "url(http://www.gravatar.com/avatar/$gravatarMd5"."?d=mm&s=62)";
		$i++;
	}
	
	if(mysql_num_rows($not_exist)){
		
		while($row = mysql_fetch_assoc($not_exist)) {
			$result[$i]['name'] = "anonymous";	
			$result[$i]['port'] = $row['port'];
			$result[$i]['model'] = $row['model'];		
			$result[$i]['avatarUrl'] = "url(images/anonymous.jpg)";
			$i++;
		}
	}
	return $result;
}	

?>